import axios from 'axios'
import type { InternalAxiosRequestConfig } from 'axios'
import { getToken } from './storage'
import { message } from 'antd'
import { parseEnvList, matchWhiteList } from './env'

// 扩展axios请求配置类型，支持loading/returnAll
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  loading?: boolean
  returnAll?: boolean
}

const DEFAULT_TIMEOUT = Number(import.meta.env.VITE_API_TIMEOUT) || 10000

// antd全局loading
let hideGlobalLoading: (() => void) | null = null
function showLoading() {
  if (!hideGlobalLoading) {
    hideGlobalLoading = message.loading({ content: '加载中...', duration: 0 })
  }
}
function hideLoading() {
  if (hideGlobalLoading) {
    hideGlobalLoading()
    hideGlobalLoading = null
  }
}

// 错误码映射
const errorMap: Record<number, string> = {
  400: '请求参数错误',
  401: '未授权，请重新登录',
  403: '没有权限',
  404: '接口不存在',
  500: '服务器错误',
}

const allowNon200: string[] = parseEnvList('VITE_ALLOW_NON200')
const allowNoToken: string[] = parseEnvList('VITE_ALLOW_NO_TOKEN')

// 获取baseURL
function getBaseUrl() {
  if (import.meta.env.DEV) return '/api'
  return window.config?.baseUrl || ''
}

// 创建axios实例
const request = axios.create({
  baseURL: getBaseUrl(),
  timeout: DEFAULT_TIMEOUT,
})

// 请求拦截器
request.interceptors.request.use(
  (config: CustomAxiosRequestConfig) => {
    // token处理，白名单内不传token
    if (!matchWhiteList(config.url, allowNoToken)) {
      const token = getToken()
      if (token) {
        config.headers = config.headers || {}
        config.headers['Authorization'] = `Bearer ${token}`
      }
    }
    // loading控制：默认开启，传loading: false可关闭
    if (config.loading !== false) showLoading()
    return config
  },
  (error) => {
    hideLoading()
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    hideLoading()
    // 只返回200的数据，除非接口在白名单或传了returnAll: true
    const { config, status, data } = response
    const returnAll = (config as CustomAxiosRequestConfig).returnAll === true
    const isWhite = matchWhiteList(config.url, allowNon200)
    if ((status === 200 && !returnAll && !isWhite) || (returnAll || isWhite)) {
      // 全局消息提示（可替换为UI库的message）
      if (data && data.message) {
        message.info(data.message)
      }
      return data
    } else {
      // 非200响应，统一错误提示
      const msg = errorMap[status] || data?.message || '请求失败'
      message.error(msg)
      return Promise.reject({ ...response, message: msg })
    }
  },
  (error) => {
    hideLoading()
    let msg = '请求失败'
    if (error.response) {
      msg = errorMap[error.response.status] || error.response.data?.message || msg
    } else if (error.message) {
      msg = error.message
    }
    message.error(msg)
    return Promise.reject(error)
  }
)

export default request 